package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.repository.StrategyCommentRepsitory;
import cn.wolfcode.wolf2w.service.IStrategyCommentService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepsitory repsitory;

    @Autowired
    private MongoTemplate template;


    @Override
    public StrategyComment get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);

        strategyComment.setCreateTime(new Date());
        repsitory.save(strategyComment);
    }


    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();


        if(StringUtils.hasLength(qo.getStrategyId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }


        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(),
                Sort.Direction.DESC, "createTime");
        return DBHelper.query(template,pageable, query,StrategyComment.class, qo);
    }


    @Override
    public void commentThumb(String cid, String uid) {

        //获取点赞id集合
        StrategyComment comment = this.get(cid);
        List<String> idList= comment.getThumbuplist();

        //判断uid是否在集合中
        if(idList.contains(uid)){
            //如果在, 点赞数 -1 移除
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            idList.remove(uid);
        }else{
            //如果不在, 点赞数 + 1, 添加
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            idList.add(uid);
        }

        //comment.setThumbuplist(idList);

        //更新
        repsitory.save(comment);

    }
}
